package cn.itcast.zt.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 信号量获取一个许可
 * create by zhangtian on 2018/4/9
 */
@Slf4j
public class SemaphoreExample1 {
    private static final int threadTotal = 20 ;

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool() ;
        final Semaphore semaphore = new Semaphore(3) ;

        for(int i = 0; i < threadTotal; i++){
            final int threadNum = i ;
            executorService.execute(()->{
                try {
                    semaphore.acquire();// 获取一个许可
                    test(threadNum);
                    semaphore.release();// 释放一个许可
                }catch (Exception e){
                    log.error("exception", e);
                }
            });

        }

        executorService.shutdown();
    }

    private static void test(int threadNum) throws Exception {
        log.info("{}", threadNum);
        Thread.sleep(1000);
    }
}
